// miniprogram/pages/payment/payment.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    item_info: {
      name: '向日葵之歌-向日葵三枝,戴安娜粉玫瑰三枝',
      price: 198.00,
      imgs: ['../../images/it1.jpg', '../../images/it2.jpg', '../../images/it3.jpg', '../../images/it4.jpg', ]
    },
    invoice_info: '',
    array: ['美国', '中国', '巴西', '日本'],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var binfo = wx.getStorageSync('buyinfo');
    var user_address = app.globalData.user_address;
    var total = 0;
    for (let i = 0; i < binfo.length; i++) {
      total += parseFloat(binfo[i].cart_buy_number * binfo[i].cart_item_price);
    }
    this.setData({
      binfo: binfo,
      user_address: user_address,
      total: total.toFixed(2)
    })
  },
  getInvoiceInfo() {
    let invoice_info = {};
    let _this = this;
    wx.chooseInvoiceTitle({
      success(res) {
        console.log(res)
        for (let i in res) {
          if (i != 'errMsg') {
            invoice_info[i] = res[i]
          }
        }
        console.log(invoice_info)
        _this.setData({
          invoice_info: invoice_info
        })
      }
    })
  },
  //获取优惠券
  getTicketsList(){
    let _this = this;
    let db = wx.cloud.database();
    wx.cloud.callFunction({
      name: 'login',
      success: res => {
        console.log(res)
        let openid = res.result.openid;
        db.collection('tb_user_list').where({ _openid: openid }).get({
          success: resp => {
            console.log(resp)
            _this.setData({
              ticket_list: resp.data[0].user_tickets
            })
          },
          fail: errp => {
            wx.showToast({
              title: '网络错误',
            })
          }
        })
      }
    }) 
  },
  //选择优惠券
  bindPickerChange(){
    
  },
  getLeaveMessage(e) {
    let val = e.detail.value;
    this.setData({
      leave_message: val
    })
  },
  wxPayment() {

  },
  submitOrder() {
    let binfo = this.data.binfo;
    let cart = this.data.binfo;
    console.log(cart)
    let buy = []
    for (let i = 0; i < binfo.length; i++) {
      let buy_info = {};
      for (let j in binfo[i]) {
        if (j != '_id' && j != '_openid') {
          buy_info[j] = binfo[i][j]
        }
      }
      buy.push(buy_info)
    }
    binfo = buy;
    console.log(binfo);
    let invoice_info = this.data.invoice_info;
    let user_address = this.data.user_address;
    let leave_message = this.data.leave_message;
    let total = this.data.total;
    let status = 1;
    let _this = this;
    let address_data = {};
    //let total = (binfo.goods_price * binfo.buy_number).toFixed(2);
    let db = wx.cloud.database();
    let time = new Date();
    let yy = time.getFullYear();
    let st = time.getTime(),
      mm = time.getMonth() + 1 > 9 ? time.getMonth() + 1 : '0' + (time.getMonth() + 1),
      dd = time.getDate() + 1 > 9 ? time.getDate() : '0' + time.getDate(),
      hh = time.getHours() > 9 ? time.getHours() : '0' + time.getHours(),
      min = time.getMinutes() > 9 ? time.getMinutes() : '0' + time.getMinutes(),
      sec = time.getSeconds() > 9 ? time.getSeconds() : '0' + time.getSeconds();
    let create_time = yy + '-' + mm + '-' + dd + ' ' + hh + ':' + min + ':' + sec;
    let order_id = st + '' + parseInt(Math.random() * 100000);
    if (!user_address.uname) {
      wx.showToast({
        title: '请选择地址',
      })
      return false;
    } else {
      for (let i in user_address) {
        if (i != '_id' && i != '_openid') {
          address_data[i] = user_address[i]
        }
      }
    }
    let data = {
      order_item_info: binfo,
      order_user_info: address_data,
      order_shipping_method: '快递物流',
      order_pay_method: '微信支付',
      order_bill_info: invoice_info ? invoice_info : '无',
      order_leave_message: leave_message ? leave_message : '',
      order_ticket_list: [],
      order_item_price: total,
      order_fare: 0,
      order_benifit: 0,
      order_vip_discount: 0,
      order_total_money: total,
      order_status: status,
      order_num: binfo.buy_number,
      order_create_time: create_time,
      order_id: order_id
    }
    console.log(data);
    db.collection('tb_order_list').add({
      data: data,
      success: res => {
        console.log(res)
        if (res.errMsg == 'collection.add:ok') {
          for (let i = 0; i < cart.length; i++) {
            console.log(cart[i]._id);
            if (cart[i]._id){
              db.collection('tb_cart_list').doc(cart[i]._id).remove();
            }
            
          }
        }
      },
      fail: err => {
        console.log(err)
      }
    })
  },
  goAddress() {
    let _this = this;
    wx.navigateTo({
      url: '../applications/address/address',
    })
  },
  

  //获取用户access_token
  getAccessToken() {
    let _this = this;
    let db = wx.cloud.database();
    wx.cloud.callFunction({
      name: 'login',
      success: res => {
        let openid = res.result.openid;
        let date = new Date();
        let nowtimestamp = date.getTime();
        db.collection('tb_user_token').where({ _openid: openid }).get({
          success: resp => {
            console.log(resp)
            if (resp.data.length > 0) {
              var timestamp = resp.data[0].timestamp;
              var id = resp.data[0]._id;
              if (nowtimestamp - timestamp > 7200 * 1000) {
                wx.cloud.callFunction({
                  name: 'sendmessage',
                  success: res => {
                    console.log(res)
                    console.log(JSON.parse(res.result))
                    let a = JSON.parse(res.result)
                    db.collection('tb_user_token').doc(id).update({
                      data: {
                        access_token: a.access_token,
                        timestamp: nowtimestamp
                      }
                    })
                    _this.setData({
                      access_token: a.access_token,
                      openid: openid
                    })
                  },
                  fail: err => {
                    console.log(err)
                  }
                })
              } else {
                _this.setData({
                  access_token: resp.data[0].access_token,
                  openid: openid
                })
              }
            } else {
              wx.cloud.callFunction({
                name: 'sendmessage',
                success: res => {
                  console.log(res)
                  let a = JSON.parse(res.result)
                  let access_token = a.access_token;
                  db.collection('tb_user_token').add({
                    data: {
                      timestamp: nowtimestamp,
                      access_token: access_token
                    },
                    success: res => {
                      console.log(res)
                    },
                    fail: err => {
                      console.log(err)
                    }
                  })
                  _this.setData({
                    access_token: access_token,
                    openid: openid
                  })
                },
                fail: err => {
                  console.log(err)
                }
              })
            }

            _this.orderSign();
          },
          fail: errp => {
            console.log(errp)
          }
        })
      },
      fail: err => {
        wx.showToast({
          title: '网络错误',
        })
      }
    })

  },
  //发送模板消息
  orderSign() {
    var fId = this.data.formId;
    var access_token = this.data.access_token;
    var openid = this.data.openid;
    var l = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' + access_token;
    var total = this.data.total;
    var order_id = this.data.order_id;
    var item_name = this.data.cart_list[0].item_name;
    console.log('temp', total + '@' + order_id + '@' + item_name)
    var date = new Date();
    var yy = date.getFullYear();
    var mm = date.getMonth() + 1 > 9 ? date.getMonth() + 1 : '0' + (date.getMonth() + 1);
    var dd = date.getDate() > 9 ? date.getDate() : '0' + date.getDate();
    var hh = date.getHours() > 9 ? date.getHours() : '0' + date.getHours();
    var min = date.getMinutes() > 9 ? date.getMinutes() : '0' + date.getMinutes();
    var sec = date.getSeconds() > 9 ? date.getSeconds() : '0' + date.getSeconds();
    var time = yy + '-' + mm + '-' + dd + ' ' + hh + ':' + min + ':' + sec;
    var ds = {
      "keyword1": {
        "value": order_id,
        "color": "#4a4a4a"
      },
      "keyword2": {
        "value": total,
        "color": "#9b9b9b"
      },
      "keyword3": {
        "value": time,
        "color": "#9b9b9b"
      },
      "keyword4": {
        "value": item_name,
        "color": "#9b9b9b"
      }
    };
    var d = {
      touser: openid,
      template_id: 'qCk4k4K5184DvJp7VgZC_6N8e9FA99wBAGsWs4ymweQ',//申请的模板消息id，
      page: '/pages/index/index',
      form_id: fId,
      data: ds,
      color: '#ccc',
      emphasis_keyword: 'keyword1.DATA'
    }
    wx.request({
      url: l,
      data: d,
      method: 'POST',
      success: function (res) {
        console.log("push msg");
        console.log(res);
      },
      fail: function (err) {
        // fail
        console.log("push err")
        console.log(err);
      }
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})